package com.js.lib_common.http;


import android.util.Log;

import com.js.lib_common.base.LibCommon;
import com.js.lib_common.constant.AppConstant;
import com.js.lib_common.mvp.model.response.LoginResponse;
import com.js.lib_common.utils.FormDataUtil;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import retrofit2.Call;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * 自动刷新token的拦截器
 */

public class TokenInterceptor implements Interceptor {

    private static final String TAG = "TokenInterceptor";

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Response response = chain.proceed(request);
        Log.d(TAG, "response.code=" + response.code());
        //根据和服务端的约定判断token过期
        if (isTokenExpired(response)) {
            Log.d(TAG, "自动刷新Token,然后重新请求数据");
            //同步请求方式，获取最新的Token
            String newToken = getNewToken();
            //使用新的Token，创建新的请求
            Request newRequest = chain.request()
                    .newBuilder()
                    .header("Authorization",  newToken)
                    .build();
            //重新请求
            return chain.proceed(newRequest);
        }
        return response;

    }

    /**
     * 根据Response，判断Token是否失效
     *
     * @param response
     * @return
     */
    private boolean isTokenExpired(Response response) {
        if (response.code() == 401) {
            return true;
        }
        return false;
    }

    /**
     * 同步请求方式，获取最新的Token
     *
     * @return
     */
    private synchronized String getNewToken() throws IOException {
        ACache  acache= ACache.get(LibCommon.mContext);
        LoginResponse user=(LoginResponse) acache.getAsObject("LoginResponse");
        // 通过获取token的接口，同步请求接口
        String newToken = "";
        ApiStores   apiStores = new Retrofit.Builder()
                .baseUrl(AppConstant.API_SCADA_URL[AppConstant.urlType])
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(new OkHttpClient.Builder().build())
                .build().create(ApiStores.class);
        Map<String, String> formMaildata = new HashMap<>();
        formMaildata.put("client_secret", "123456");
        formMaildata.put("client_id", "user-service");
        formMaildata.put("refresh_token", user.getRefresh_token());
        formMaildata.put("grant_type", "refresh_token");
        Map<String, RequestBody> stringRequestBodyMap = FormDataUtil.generateRequestBody(formMaildata);

        Call<LoginResponse>  call=apiStores.refreshToken(stringRequestBodyMap);
        //同步
        LoginResponse response=call.execute().body();
        if(response!=null){
            newToken=  response.getToken_type()+" "+ response.getAccess_token();
            acache.put("LoginResponse",response);
            Log.d(TAG, "token刷新成功" );
        }


        return newToken;
    }
}